import { USERINFO_GET } from '../../api/index'
import router from '../../router/index'
import request from '../../utils/request'
export const userStore = {
    state() {
        return{
            menus: [],//未处理的后台菜单数据
            username:localStorage.getItem('username')||''
        }
    },
    mutations: {
        setUserMenus(state, value) {
            if (value) {
                state.menus = value
            }

        },
        setUsername(state,value){
            if (value) {
               state.username=value
            }
        },
    },
    actions: {
        getUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                request({
                    url: USERINFO_GET,
                    method: 'get'
                }).then((res) => {
                    if (res.code == 200 && res.data) {
                        commit('setUserMenus', res.data.menus)
                        commit('setUsername',res.data.username)
                        localStorage.setItem('username', res.data.username)
                        resolve(res.data)
                    }
                })

            })

        }
    },
    getters: {
        //将返回菜单格式进行树状调整
        getNewMenus({ menus }) {
            //格式化菜单数据
            let newMenus = []//树状数据
            for (let i = 0; i < menus.length; i++) {
                const el = menus[i]
                if (el.parentId === 0) {
                    el.children = []
                    newMenus.push(el)
                }
            }
            for (let i = 0; i < newMenus.length; i++) {
                const firstItem = newMenus[i];
                for (let j = 0; j < menus.length; j++) {
                    const secondItem = menus[j];
                    if (firstItem.id == secondItem.parentId) {
                        firstItem.children.push(secondItem)
                    }

                }
            }
        
            return newMenus
        },
       
    }
}